package com.example.car.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.car.R
import com.example.car.bean.TitleInfo
import com.example.car.databinding.SubItemBinding
import com.example.car.db.SubDbHelper

class SubChannelAdapter : RecyclerView.Adapter<SubChannelAdapter.ViewHolder>() {
    private lateinit var binding: SubItemBinding

    inner class ViewHolder : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        binding = SubItemBinding.inflate(inflater, parent, false)
        return ViewHolder()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val bind = SubItemBinding.bind(holder.itemView)
        val subDbHelper = SubDbHelper.getInstance(bind.root.context)
        bind.apply {
            var isAddState = 1
            tvTitle.text = differ.currentList[position].title
            // 已订阅
            if (differ.currentList[position].is_sub == 1) {
                ivAdd.setImageResource(R.drawable.ic_baseline_remove_24)
            }
            // 订阅点击按钮
            ivAdd.setOnClickListener {
                // 默认订阅前两个
                val defaut_title = differ.currentList[position].title
                if (defaut_title == "推荐" || defaut_title == "国内") {
                    return@setOnClickListener
                }
                if (isAddState == 1) {
                    ivAdd.setImageResource(R.drawable.ic_baseline_remove_24)
                    subDbHelper.updateSub(differ.currentList[position].id!!, 1)
                    isAddState = 0
                } else {
                    ivAdd.setImageResource(R.drawable.ic_baseline_add_25)
                    subDbHelper.updateSub(differ.currentList[position].id!!, 0)
                    isAddState = 1
                }
            }
        }
    }

    override fun getItemCount() = differ.currentList.size

    val differ = AsyncListDiffer(this, object : DiffUtil.ItemCallback<TitleInfo>() {
        override fun areItemsTheSame(oldItem: TitleInfo, newItem: TitleInfo): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: TitleInfo, newItem: TitleInfo): Boolean {
            return oldItem == newItem
        }
    })
}